﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;

namespace BookItems.Site
{
	public class Global : System.Web.HttpApplication
	{
		void Application_Start(object sender, EventArgs e)
		{
            InitActiveRecord();
		}

        private static void InitActiveRecord()
        {
            int initAttempts = 0;
            try
            {
                // Initialise ActiveRecord
                XmlConfigurationSource source = new XmlConfigurationSource(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("BookItems.Site.ActiveRecordConfig.xml"));
                source.IsRunningInWebApp = true;
                //source.SetDebugFlag(true);

                ActiveRecordStarter.Initialize(source,
                    typeof(BookItems.Core.Booking),
                    typeof(BookItems.Core.BookableItem),
                    typeof(BookItems.Core.NewsItem),
                    typeof(BookItems.Core.User));

                //ActiveRecordStarter.Initialize(System.Reflection.Assembly.GetAssembly(typeof(BookItems.Core.User)), source);

                ActiveRecordStarter.UpdateSchema();
            }
            catch (Exception) // TODO Log exception
            {
                if (initAttempts++ < 10)
                    InitActiveRecord();
            }
        }

		void Application_End(object sender, EventArgs e)
		{
			//  Code that runs on application shutdown

		}

		void Application_Error(object sender, EventArgs e)
		{
            Exception ex = HttpContext.Current.Server.GetLastError();


            Server.ClearError();
		}

		void Application_BeginRequest(object sender, EventArgs e)
		{
			HttpContext.Current.Items.Add("ar.sessionscope", new SessionScope());
		}
		
		void Application_EndRequest(object sender, EventArgs e)
		{
			try
			{
				var scope = HttpContext.Current.Items["ar.sessionscope"] as SessionScope;
				if (scope != null)
					scope.Dispose();
			}
			catch (Exception ex)
			{
				HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
			}
		}

		void Session_Start(object sender, EventArgs e)
		{
			// Code that runs when a new session is started
			//HttpContext.Current.Items.Add("ar.sessionscope", new SessionScope());
		}

		void Session_End(object sender, EventArgs e)
		{
			// Code that runs when a session ends. 
			// Note: The Session_End event is raised only when the sessionstate mode
			// is set to InProc in the Web.config file. If session mode is set to StateServer 
			// or SQLServer, the event is not raised.
			/*
			try
			{
				var scope = HttpContext.Current.Items["ar.sessionscope"] as SessionScope;
				if (scope != null)
					scope.Dispose();
			}
			catch (Exception ex)
			{
				HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
			}*/
		}
	}
}
